<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Backend_ProductController
 *
 * @author Eugene
 */
class Backend_ProductController extends Zend_Controller_Action
{

	/**
	 * @var Application_Model_Mapper_Product
	 */
	protected $_mapper;

	/**
	 *
	 * @return Application_Model_Mapper_Product
	 */
	public function getMapper()
	{
		if (null === $this->_mapper) {
			$this->_mapper = new Application_Model_Mapper_Product;
		}

		return $this->_mapper;
	}

	/**
	 *
	 * @return void
	 */
	public function indexAction()
	{
		$messages = $this->_helper->flashMessenger->getMessages();
		$messages = array_flip($messages);

		$this->view->messages = $messages;
		$this->view->entries = $this->getMapper()->fetchAll();
	}

	/**
	 *
	 * @return void
	 */
	public function createAction()
	{
		$form = new Backend_Form_Product_Create;

		// form brands
		$brandMapper = new Application_Model_Mapper_Brand;
		foreach ($brandMapper->fetchAll() as $brandEntry) {
			$form->getElement('brandId')->addMultiOption(
					$brandEntry->id, $brandEntry->name
			);
		}

		// form categories
		$categoryMapper = new Application_Model_Mapper_Category;
		$categorySelect = $categoryMapper->getDbTable()
				->select()
				->columns('id, name')
				->where('enabled = ?', 1);
		$categoryEntries = $categoryMapper->getDbTable()
				->fetchAll($categorySelect);
		foreach ($categoryEntries as $categoryEntry) {
			$form->getElement('categories')->addMultiOption(
					$categoryEntry->id, $categoryEntry->name
			);
		}

		if ($this->getRequest()->isPost()) {
			if ($form->isValid($this->getRequest()->getPost())) {
				$model = new Application_Model_Product($form->getValues());
				$this->getMapper()->save($model);

				$this->_helper->FlashMessenger('created');
				return $this->_helper->redirector('index');
			}
		}

		$this->view->form = $form;
	}

}